

import 'package:erp/Entity/WareHouse.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/WareHouse.dart';
import 'package:erp/global.dart';

void registerWareHouseEvents(){

  globalBus.subscribe<WareHouse>(Events.WAREHOUSE_INSERT_REQUEST, (bus, data) async {
    try {
      var responseData = await externalInterface.addWareHouses(AccountStore.signInResult.token, data);
      WareHouseStore.wareHouses.add(responseData);
      globalBus.publish(Events.WAREHOUSE_INSERT_SUCCESS, responseData);
    }
    catch (exception){
      globalBus.publish(Events.WAREHOUSE_INSERT_ERROR, exception);
    }
  });
  
  globalBus.subscribe(Events.WAREHOUSE_SELECT_REQUEST, (bus, _)async {
    try {
      var count = await externalInterface.getAllWareHouseCount(AccountStore.signInResult.token);
      var list = List<WareHouse>();
      for (var index = 0; index < count.allPageCount; index++){
        list.addAll(await externalInterface.getWareHouses(AccountStore.signInResult.token, index));
      }
      WareHouseStore.wareHouses = list;
      globalBus.publish(Events.WAREHOUSE_SELECT_SUCCESS, list);
    }
    catch (exception){
      globalBus.publish(Events.WAREHOUSE_SELECT_ERROR, exception);
    }
  });

  globalBus.subscribe<WareHouse>(Events.WAREHOUSE_UPDATE_REQUEST, (bus, wareHouse) async {
    try {
      var data = await externalInterface.updateWareHouses(AccountStore.signInResult.token, wareHouse);
      var index = WareHouseStore.wareHouses.indexWhere((item) => item.id == data.id);
      WareHouseStore.wareHouses[index] = data;
      globalBus.publish(Events.WAREHOUSE_UPDATE_SUCCESS, data);
    }
    catch (exception){
      globalBus.publish(Events.WAREHOUSE_UPDATE_ERROR, exception);
    }
  });

  globalBus.subscribe<WareHouse>(Events.WAREHOUSE_DELETE_REQUEST, (bus, wareHouse) async {
    try {
      var data = await externalInterface.deleteWareHouses(AccountStore.signInResult.token, wareHouse);
      WareHouseStore.wareHouses.removeWhere((item) => item.id == data.id);
      globalBus.publish(Events.WAREHOUSE_DELETE_SUCCESS, data);
    }
    catch (exception) {
      globalBus.publish(Events.WAREHOUSE_DELETE_ERROR, exception);
    }
  });
}
